package com.zky.config;

import com.zky.enums.VMTypes;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.FileWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class CrudGenerator {
    public static Map<String,String> typeMap = new HashMap<>();
    private static final String entityName = "User";
    private static final String  entityNameLower = entityName.substring(0,1).toLowerCase() + entityName.substring(1);
    private static final VelocityContext ctx = new VelocityContext();
    private static String fullPath;
    private static final String[] TYPES_ARRS = {"mapper", "service", "ServiceImpl", "controller"};
    static {
        ctx.put("tags", entityName);
        ctx.put("entityName", entityName);
        ctx.put("entityNameLower", entityNameLower);
        ctx.put("idType", "Integer");

    }
    public static void main(String[] args) throws Exception {
        // 初始化 Velocity
        Properties props = new Properties();
        props.setProperty("file.resource.loader.path", "src/main/resources/templates"); // 模板路径
        VelocityEngine ve = new VelocityEngine(props);
        ve.init();

        for(int i=0;i<TYPES_ARRS.length;i++) {
            String type = TYPES_ARRS[i];
            typeMap.put("type",type);
            String outputPath = "src/main/java/com/zky/"+type+"/";
            if(typeMap.get("type").equals(VMTypes.SERVICEIMPL.toString())){
                outputPath = "src/main/java/com/zky/service/"+"impl/";
            }
            fullPath = outputPath + entityName +typeMap.get("type").substring(0,1).toUpperCase()+typeMap.get("type").substring(1)+".java";
            // 加载模板
            Template template = ve.getTemplate(typeMap.get("type")+".vm", "UTF-8");
            // 渲染模板
            StringWriter writer = new StringWriter();
            template.merge(ctx, writer);
            // 输出到文件
            try (FileWriter fileWriter = new FileWriter(fullPath)) {
                fileWriter.write(writer.toString());
            }
            System.out.println("代码已生成: "+fullPath);
        }

    }
}
